//
//  FirstViewController.swift
//  AreaChainblock
//
//  Created by 赵佟越 on 2018/9/12.
//  Copyright © 2018年 zhaotongyue. All rights reserved.
//

import UIKit
import FSPagerView
import SwiftyUserDefaults
class FirstViewController: BaseViewController ,UITableViewDataSource, UITableViewDelegate ,FSPagerViewDelegate,FSPagerViewDataSource{
    var myModel = firstViewModel()
    var rollView: YPRollNoticeView?
    var imageArr = ["THTC币","组 1","组 6"]
    var titleArr = ["DKE","CD","MT"]
    var lunBoArr = NSArray()
    var tempArr = NSMutableArray()
    var tempArrWeb = NSMutableArray()
    
    fileprivate let imageNames = ["1539145853115.jpg"]
    
    var  pageControl = FSPageControl()
    var dataArr = NSArray()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        makeBaseUI()
        getDataGongGao()
        layoutNav()
        
        // Do any additional setup after loading the view.
    }
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.isNavigationBarHidden = true
        getData()
        getDataGongGao()
        
    }
    
    func getDataGongGao() {
        MyNetwork.request(target: .getList(page: "1", limit: "100", user_id: Defaults[.userID]!), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            
            if needModel.code == 1111{
                self.tempArr = NSMutableArray()
                self.tempArrWeb = NSMutableArray()
                var tempArr1 = NSMutableArray.yy_modelArray(with: productModel.self, json: needModel.mydata!["data"]!)
                for tempModel in tempArr1!{
                   
                    if XALanguageManager.getString(key: "语种") == "English" {
                        self.tempArr.add((tempModel as! productModel).e_title as! String)
                        
                    }else{
                        self.tempArr.add((tempModel as! productModel).title as! String)
                        
                    }
                    
                    
                    self.tempArrWeb.add((tempModel as! productModel).url as! String)
                }
                
                self.rollView!.rollArray = self.tempArr as! [String]
//                self.lunBoArr = (((result as AnyObject)["data"]as AnyObject)["carousel_list"] as! NSArray)
            }
            
            
        }) { (error) in
            kLog(error.localizedDescription)
        }
    }
    
    //MARK: - Private Method
    func getData() {
        MyNetwork.request(target: .home(user_id: Defaults[.userID]!), success: { (result) in
            kLog(result)
            let needModel = BaseModel()
            needModel.yy_modelSet(with: result as! [AnyHashable : Any])
            
            if needModel.code == 1111{
                self.myModel.yy_modelSet(withJSON: ((result as AnyObject)["data"]as AnyObject)["data"])
                
                Defaults[.allDKE] = self.myModel.dke
                
                self.lunBoArr = (((result as AnyObject)["data"]as AnyObject)["carousel_list"] as! NSArray)
                
                
                self.myTableView.reloadData()
            }
            
            
        }) { (error) in
            kLog(error.localizedDescription)
        }
    }
    
        
    func makeBaseUI() -> Void {
        self.view.addSubview(myTableView)
        
        let imageLaba = UIImageView(frame: CGRect(x: 30, y: 240*_kScreenWidth + 17.5, width: 15, height: 15))
        
        
        
        imageLaba.image = UIImage.init(named: "laba@2x")
        self.view.addSubview(imageLaba)
        
        
        rollView = YPRollNoticeView.init(frame: CGRect.init(x: 20 + 40, y: 240 * _kScreenWidth + 10, width: kScreenWidth - 40-40, height: 30))
        rollView!.backgroundColor = UIColor.clear
        rollView?.labelOne.textColor = UIColor("#C1C3C9")
        rollView?.labelTwo.textColor = UIColor("#C1C3C9")
        rollView!.clickBlock = { index in
            print("点击了\(index)")
            
            let MyWebVC = MyTongZhiListViewController()
//            MyWebVC.title = self.tempArr[Int(index)] as! NSString as String;
            
//            MyWebVC.urlStr = self.tempArrWeb[index] as! NSString
            self.navigationController?.pushViewController(MyWebVC, animated: true)
            
        }
        self.view.addSubview(rollView!)
//        rollView!.rollArray = ["习近平同美国总统特朗普通电话","习近平鼓励民营企业安心谋发展 走向更广阔舞台","@所有公务员,关于你的职务职级养老等,或有新变化!","扬州国资委原主任被公诉，曾遭儿子前女友举报“豪宅成排”","13人因猎捕癞蛤蟆破坏生态坏境被追究刑事责任"]
        
    }
    func layoutNav(){
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        tabBarController?.title = "11"
        navigationController?.navigationBar.subviews[0].removeFromSuperview()//去掉NavigationBar的背景和横线
    }
    
    //MARK: - tableView Delegate And DataSource
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell:firstViewControllerTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "cell")as?firstViewControllerTableViewCell
        if cell == nil {
            cell = firstViewControllerTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
            cell.selectedBackgroundView = UIView(frame: cell.frame);
            cell.selectedBackgroundView?.backgroundColor = UIColor("#070E33")
        }
        if indexPath.row == 2{
            cell.LineView.isHidden = true
        }else{
            cell.LineView.isHidden = false
        }
        
        cell.coverImageView?.image = UIImage.init(named: imageArr[indexPath.row])
        
        cell.titleLab?.text = titleArr[indexPath.row]
        cell.accessoryType = .disclosureIndicator
        if indexPath.row == 0 {
            if myModel.dke == nil{
                
            }else{
                cell?.priceLab?.text = String(format: "%.3f", Float(myModel.dke as String!)!)
            }
            
            
            
        }else if indexPath.row == 1{
            if myModel.m == nil{
                
            }else{
                cell?.priceLab?.text = String(format: "%.3f", Float(myModel.m as String!)!)
            }
            
           
        }else{
            if myModel.n == nil{
                
            }else{
                cell?.priceLab?.text = String(format: "%.3f", Float(myModel.n as String!)!)
            }
            
            
        }
        
        
        return cell!
    }
    //footer height
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    // row height
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return nil
    }
    
    // row num
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    // 组数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    //点击事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if Defaults[.isLogInKey] == false{
            super.LogIn()
            return
        }
        if myModel.dke == nil {
            return
        }

        if indexPath.row == 0 {
            let DkeVC = DKEViewController()
            DkeVC.nameLaeblStr = myModel.dke! as NSString; self.navigationController?.pushViewController(DkeVC, animated: true)
        }else if indexPath.row == 1{
            let MVC = MViewController()
            MVC.nameLaeblStr = myModel.m! as NSString; self.navigationController?.pushViewController(MVC, animated: true)
        }else{
            let NVC = NViewController()
            NVC.LabelStr = myModel.n! as NSString; self.navigationController?.pushViewController(NVC, animated: true)
        }
    }
    
    override func willMove(toParentViewController parent: UIViewController?) {
        
    }
    // header height
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 250 * _kScreenWidth + 20
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let mybackView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 250 * _kScreenWidth))
        mybackView.backgroundColor = UIColor.clear
        
        // Create a pager view
        let pagerView = FSPagerView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 250 * _kScreenWidth))
        pagerView.dataSource = self
        pagerView.delegate = self
        pagerView.isInfinite = true
        pagerView.interitemSpacing = 15
        pagerView.automaticSlidingInterval = 1000000
        pagerView.transformer = FSPagerViewTransformer(type: .crossFading)
        pagerView.itemSize = CGSize(width: kScreenWidth , height:180 * _kScreenWidth)
        pagerView.clipsToBounds = true
        
        pagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        mybackView.addSubview(pagerView)
        // Create a page control
        self.pageControl = FSPageControl(frame: CGRect(x: 0, y: 230 * _kScreenWidth, width: kScreenWidth, height: 15))
        self.pageControl.setFillColor(UIColor.blue, for: .normal)
        self.pageControl.setFillColor(.gray, for: .selected)
        //self.pageControl.setFillColor(.green, for: .selected)
        self.pageControl.numberOfPages = 0
        mybackView.addSubview(self.pageControl)
        return mybackView
    }
    // MARK:- FSPagerViewDataSource
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return self.imageNames.count
    }
    
    public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
        cell.imageView?.image = UIImage(named: self.imageNames[index])
        var url1:URL
        if self.lunBoArr.count > 0 {
            url1 = URL( string:String(format: "http://renedescartes.io%@", (self.lunBoArr[0] as! Dictionary<NSString, Any>)["img"]! as! CVarArg))!
        }else{
            url1 = URL(string: "123")!
        }
        
        cell.imageView?.sd_setImage(with: url1, placeholderImage: UIImage.init(named: "1"), options: [], progress: nil, completed:nil)
//        cell.imageView?.image = UIImage(named: "1")
        let dkeLabel = UILabel(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 180))
        dkeLabel.textColor = UIColor.white
        dkeLabel.text = "DKE Planet"
        dkeLabel.font = UIFont.boldSystemFont(ofSize: 49)
        dkeLabel.textAlignment = .center
        cell.addSubview(dkeLabel)
        cell.imageView?.contentMode = .scaleAspectFill
        return cell
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
    }
    
    // MARK:- FSPagerViewDelegate
    
    func pagerViewDidScroll(_ pagerView: FSPagerView) {
        guard self.pageControl.currentPage != pagerView.currentIndex else {
            return
        }
        
        self.pageControl.currentPage = pagerView.currentIndex // Or Use KVO with property "currentIndex"
    }
    
    // MARK: - 懒加载
    private lazy var myTableView:UITableView = {
        let myTableView:UITableView
        if(UIDevice.current.isX()){
            myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight - 49), style: UITableViewStyle.grouped)
        }else{
             myTableView = UITableView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight - 49), style: UITableViewStyle.grouped)
        }
        myTableView.isScrollEnabled = false
        myTableView.delegate = self
        myTableView.dataSource = self
        myTableView.backgroundColor = UIColor.clear
        myTableView.separatorStyle = .none
        myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        return myTableView
    }()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
